package com.shigu.admin.manager.services;

import com.opentae.data.mall.beans.ManagerRole;
import com.opentae.data.mall.beans.ManagerRolePermission;
import com.opentae.data.mall.beans.RolePermission;
import com.opentae.data.mall.examples.ManagerRoleExample;
import com.opentae.data.mall.examples.ManagerRolePermissionExample;
import com.opentae.data.mall.interfaces.ManagerPermissionMapper;
import com.opentae.data.mall.interfaces.ManagerRoleMapper;
import com.opentae.data.mall.interfaces.ManagerRolePermissionMapper;
import com.shigu.component.shiro.AuthorityUser;
import com.shigu.admin.manager.common.CustomPager;
import com.shigu.admin.manager.utils.PageUtil;
import com.shigu.admin.manager.vo.RoleVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 处理角色的服务
 * Created by zhaohongbo on 16/5/13.
 */
@Service
public class AdminRoleService {

    @Autowired
    ManagerRoleMapper managerRoleMapper;

    @Autowired
    ManagerPermissionMapper managerPermissionMapper;

    @Autowired
    ManagerRolePermissionMapper managerRolePermissionMapper;

    /**
     * 检测角色名是否被使用过
     * @param roleName
     * @return
     */
    @RequiresPermissions("role:add")
    public ManagerRole checkRoleNameAndTag(String roleName, String roleTag){
        ManagerRoleExample example=new ManagerRoleExample();
        example.createCriteria().andRoleNameEqualTo(roleName);
        example.or().andRoleTagEqualTo(roleTag);
        List<ManagerRole> list=managerRoleMapper.selectByExample(example);
        if(list.size()>0){
            return list.get(0);
        }
        return null;
    }

    /**
     * 添加权限标签
     * @return
     */
    @RequiresPermissions("role:add")
    public Long addRole(String roleName,String roleTag,String tagComment){
        ManagerRole mp=new ManagerRole();
        mp.setCreateTime(new Date());
        mp.setStatus(1);
        mp.setRoleComment(tagComment);
        mp.setRoleName(roleName);
        mp.setRoleTag(roleTag);
        Subject currentUser = SecurityUtils.getSubject();
        AuthorityUser auth = (AuthorityUser) currentUser.getPrincipal();
        mp.setCreateUserId(auth.getUserId());
        managerRoleMapper.insertSelective(mp);
        return mp.getRoleId();
    }

    /**
     * 修改角色和权限之间的关系
     * @param uid
     * @param pid
     * @return
     */
    @RequiresPermissions("role:modify")
    public int changeRelation(Long uid,Long pid){
        ManagerRolePermissionExample example=new ManagerRolePermissionExample();
        example.createCriteria().andPermissionIdEqualTo(pid).andRoleIdEqualTo(uid);
        List<ManagerRolePermission> list=managerRolePermissionMapper.selectByExample(example);
        if(list.size()>0){//需要解除关系
            managerRolePermissionMapper.deleteByExample(example);
            return 0;
        }else{//添加关系
            ManagerRolePermission mrp=new ManagerRolePermission();
            mrp.setRoleId(uid);
            mrp.setCreateTime(new Date());
            mrp.setPermissionId(pid);
            managerRolePermissionMapper.insertSelective(mrp);
            return 1;
        }
    }

    /**
     * 查角色的权限
     * @param roleId
     * @return
     */
    @RequiresPermissions("role:modify")
    public List<RolePermission> selPermissionByRoleId(Long roleId){
        return managerPermissionMapper.selPermissiontagsByroleIds(roleId.toString());
    }

    /**
     * 查角色的权限,查一定范围内的
     * @param roleId
     * @return
     */
    @RequiresPermissions("role:modify")
    public List<RolePermission> selPermissionByRoleIdAndPids(Long roleId,String pids){
        return managerPermissionMapper.selPermissiontagsByroleIdsAndPid(roleId.toString(), pids);
    }
    /**
     * 查角色
     * @return
     */
    @RequiresPermissions("role:list")
    public CustomPager<RoleVO> selRoles(String keyword,Integer pageNo,Integer pageSize,Integer status){
        ManagerRoleExample example=new ManagerRoleExample();
        example.setOrderByClause("role_id desc");
        if(keyword!=null){
            if(status==null){
                example.createCriteria().andRoleNameLike("%" + keyword + "%");
                example.or().andRoleCommentLike("%" + keyword + "%");
            }else{
                example.createCriteria().andRoleNameLike("%" + keyword + "%").andStatusEqualTo(status);
                example.or().andRoleCommentLike("%" + keyword + "%").andStatusEqualTo(status);
            }
        }else if(status!=null){
            example.createCriteria().andStatusEqualTo(status);
        }
        example.setStartIndex((pageNo - 1) * pageSize);
        example.setEndIndex(pageSize);
        int total=managerRoleMapper.countByExample(example);
        List<ManagerRole> mulist=managerRoleMapper.selectByConditionList(example);
        Map<Long,RoleVO> vomap=new HashMap<Long, RoleVO>();
        String roleIds="";
        for(ManagerRole mu:mulist){
            roleIds+=","+mu.getRoleId();
            RoleVO uv=new RoleVO();
            uv.setRoleId(mu.getRoleId());
            uv.setCreateTime(mu.getCreateTime());
            uv.setRoleComment(mu.getRoleComment());
            uv.setStatus(mu.getStatus());
            uv.setRoleName(mu.getRoleName());
            uv.setRoleTag(mu.getRoleTag());
            uv.setRolePermissions(new ArrayList<RolePermission>());
            vomap.put(mu.getRoleId(),uv);
        }
        if(roleIds.length()>0){
            roleIds=roleIds.substring(1);
        }
        List<RolePermission> roleList=new ArrayList<RolePermission>();
        if(!roleIds.equals("")){
            roleList=managerPermissionMapper.selPermissiontagsByroleIds(roleIds);
        }
        for(RolePermission ur:roleList){
            RoleVO uv=vomap.get(ur.getRoleId());
            List<RolePermission> roles=uv.getRolePermissions();
            roles.add(ur);
        }
        CustomPager<RoleVO> pager=new CustomPager<RoleVO>();
        List<RoleVO> userlist=new ArrayList<RoleVO>();
        userlist.addAll(vomap.values());
        pager.setNumber(pageNo-1);
        pager.setTotalPages(PageUtil.calPage(pageSize, total));
        pager.setContent(userlist);
        return pager;
    }

    /**
     * 修改用户状态
     * @param pid
     * @return
     */
    @RequiresPermissions("role:modify")
    public int changeRoleStatus(Long pid){
        ManagerRole user=managerRoleMapper.selectByPrimaryKey(pid);
        if(user==null){
            return 0;
        }
        user.setStatus((user.getStatus()+1)%2);
        managerRoleMapper.updateByPrimaryKeySelective(user);
        return 1;
    }
}
